var express = require("express");
const { get } = require("../api/commodity");
var router = express.Router();
// 引入远程接口的调用方法
const CommodityApi = require("../api/commodity");

// 获取商品数据 ， get 类型
router.get("/", async function (req, res, next) {
    const { curPage, eachPage } = req.query;
    const data = await get({ curPage, eachPage });
    res.send(data);
})

// 新增商品数据， post 类型
router.post('/add', async function (req, res, next) {
    const { name, guarantee, storeCondition, aftersale, place, specs, pack, sales, desc } = req.body;
    const data = await CommodityApi.addCommodity({ name, guarantee, storeCondition, aftersale, place, specs, pack, sales, desc });
    res.send(data)
});

// 删除商品数据
router.delete("/remove", async function (req, res, next) {
    const { _id } = req.body;
    const status = await CommodityApi.delCommodity({ _id });
    res.send(status);
})

//通过名称查找商品
router.get("/find", async function (req, res, next) {
    const { name } = req.query;
    const data = await CommodityApi.findCommodity(name);
    res.send(data);
})

// 修改商品数据
router.put("/edit", async function (req, res, next) {
    const newData = req.body;
    await CommodityApi.editCommodity(newData);
    res.send({ status: true })
})


// 更新图片数据
router.post('/addImg', async function (req, res, next) {
    // 从url拿参数
    const { _id, url } = req.body;

    // 传值更新
    await CommodityApi.uploadImgs({ _id, url });
    // 返回更新的整条数据
    const result = await CommodityApi.findOne({ _id });
    res.send(result)
});

// 删除照片路由commodity/delImg
router.delete('/delImg', async function (req, res, next) {
    // 从url拿参数
    const { _id, url } = req.body;
    await CommodityApi.delImgs({ _id, url });
    //获取到修改保存后的最新数据并返回
    const data = await CommodityApi.findOne({ _id });
    res.send(data);
});
// 修改商品所属类型
router.patch("/resComType", async (req, res, next) => {
    const { _id, Child_type } = req.body
    const data = await CommodityApi.resComType({ _id, Child_type })
    res.send(data)
})


// 删除详情图片
router.delete('/deleteDetailsImg', async function (req, res, next) {
    // 从url拿参数
    const { _id, url } = req.body;
    await CommodityApi.deleteDetailsImg({ _id, url });
    //获取到修改保存后的最新数据并返回
    const data = await CommodityApi.findOne({ _id });
    res.send(data);
});

// 更新详情图片数据
router.post('/addDetailsImg', async function (req, res, next) {
    // 从url拿参数
    const { _id, url } = req.body;

    // 传值更新
    await CommodityApi.uploadDetailsImgs({ _id, url });
    // 返回更新的整条数据
    const result = await CommodityApi.findOne({ _id });
    res.send(result)
});





module.exports = router;